<?php

class SupplyController extends Zend_Controller_Action {

    public function init() {
        $ajaxContext = $this->_helper->getHelper("AjaxContext");
        $ajaxContext->addActionContext("getsupplytype", "json");
        $ajaxContext->addActionContext("getsupplytypefactor", "json");
        $ajaxContext->addActionContext("save", "json");
        $ajaxContext->addActionContext("getsupplylist", "json");
        $ajaxContext->addActionContext("getsupply", "json");
        $ajaxContext->addActionContext("deletesupply", "json");
        $ajaxContext->addActionContext('fileupload', "html");
        $ajaxContext->addActionContext('export', "html");
        $ajaxContext->initContext();
    }

    public function getsupplytypeAction() {
        $supplytype = new Application_Model_DbTable_SupplyType();
        $this->_helper->getHelper('Json')->sendJson($supplytype->fetchAll()->toArray());
    }

    public function getsupplytypefactorAction() {
        $supplyTypeId = $this->getRequest()->getParam("supplytypeid");
        $supplyid = $this->getRequest()->getParam("supplyid");
        $supplytype = new Application_Model_DbTable_SupplyType();
        $this->_helper->getHelper('Json')->sendJson($supplytype->getSupplyTypeFactor($supplyTypeId, $supplyid));
    }

    public function saveAction() {
        $id = $this->getRequest()->getParam("ID");
        $data = array(
            'Ref' => $this->getRequest()->getParam("Ref"),
            'Name' => $this->getRequest()->getParam("Name"),
            'Supplier' => $this->getRequest()->getParam("Supplier"),
            'Price' => doubleval($this->getRequest()->getParam("Price")),
            'Comments' => $this->getRequest()->getParam("Comments"),
            'SuppylyTypeId' => intval($this->getRequest()->getParam("SuppylyTypeId")),
            'Unit' => $this->getRequest()->getParam("Unit"),
            'Weight' => doubleval($this->getRequest()->getParam("Weight")),
            'UpateTime' => date('Y-m-d H:i:s')
        );

        $supply = new Application_Model_DbTable_Supply();
        $supplyRanking = new Application_Model_DbTable_SupplyRanking();
        if (empty($id)) {
            $data['CreateTime'] = date('Y-m-d H:i:s');
            $supply->insert($data);
            $id = $supply->getAdapter()->lastInsertId();
            $factor = $this->getRequest()->getParam("factor");
            if (strlen($factor) > 0) {
                $factors = explode(';', $factor);
                if (count($factors) > 0) {
                    foreach ($factors as $value) {
                        $key = explode(',', $value);
                        $supplyRankData = array(
                            'SupplyID' => intval($id),
                            'RankingRuleID' => intval($key[0]),
                            'RankingGrade' => doubleval($key[1])
                        );
                        $supplyRanking->insertRow($supplyRankData);
                        unset($supplyRankData);
                    }
                }
            }
        } else {
            $where = $supply->getAdapter()->quoteInto(' ID = ?', intval($id));
            $supply->update($data, $where);
            $factor = $this->getRequest()->getParam("factor");
            if (strlen($factor) > 0) {
                $factors = explode(';', $factor);
                if (count($factors) > 0) {
                    $delete = $supply->getAdapter()->quoteInto('SupplyID = ?', intval($id));
                    $supplyRanking->delete($delete);
                    foreach ($factors as $value) {
                        $key = explode(',', $value);
                        $supplyRankData = array(
                            'SupplyID' => intval($id),
                            'RankingRuleID' => intval($key[0]),
                            'RankingGrade' => intval($key[1])
                        );
                        $supplyRanking->insertRow($supplyRankData);
                        unset($supplyRankData);
                    }
                }
            }
        }
        $this->_helper->getHelper('Json')->sendJson(array('id' => $id, 'message' => 'Save Successfully'));
    }

    public function fileuploadAction() {
        $id = $this->getRequest()->getParam("sid");
        $allowedExts = array("jpg", "jpeg", "gif", "png");
        $name = $_FILES["file"]["name"];
        $extension = substr($name, strrpos($name, '.') + 1);
        $filename = 'supply' . uniqid($id) . '.' . $extension;
        if ((($_FILES["file"]["type"] == "image/gif")
                || ($_FILES["file"]["type"] == "image/jpeg")
                || ($_FILES["file"]["type"] == "image/pjpeg")
                || ($_FILES["file"]["type"] == "image/png"))
                && in_array($extension, $allowedExts)) {

            $supply = new Application_Model_DbTable_Supply();
            $result = $supply->find($id);
            $sp = $result->toArray();
            $photo = $sp[0]['Photo'];
            if (file_exists(UPLOAD_PATH . DIRECTORY_SEPARATOR . $photo)) {
                @unlink(UPLOAD_PATH . DIRECTORY_SEPARATOR . $photo);
            }
            move_uploaded_file($_FILES["file"]["tmp_name"], UPLOAD_PATH . DIRECTORY_SEPARATOR . $filename);
        }

        $data = array("photo" => $filename);
        $supply = new Application_Model_DbTable_Supply();
        $where = $supply->getAdapter()->quoteInto(' id = ?', $id);
        $supply->update($data, $where);
        Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true);
        Zend_Layout::getMvcInstance()->disableLayout();
        $response = '<textarea>' . $filename . '</textarea>';
        $this->getResponse()->setBody($response);
    }

    public function getsupplylistAction() {
        $supplyTypeId = $this->getRequest()->getParam("type");
        $supply = new Application_Model_DbTable_Supply();
        $this->_helper->getHelper('Json')->sendJson(array_values($supply->getAllSupply($supplyTypeId)));
    }

    public function getsupplyAction() {
        $sid = $this->getRequest()->getParam("sid");
        $supply = new Application_Model_DbTable_Supply();
        $this->_helper->getHelper('Json')->sendJson($supply->getSupply($sid)->toArray());
    }

    public function deletesupplyAction() {
        $sid = $this->getRequest()->getParam("sid");
        if (!empty($sid)) {
            $supply = new Application_Model_DbTable_Supply();
            $result = $supply->find($sid);
            $sp = $result->toArray();
            $photo = $sp[0]['Photo'];
            if (file_exists(UPLOAD_PATH . DIRECTORY_SEPARATOR . $photo)) {
                @unlink(UPLOAD_PATH . DIRECTORY_SEPARATOR . $photo);
            }
            $where = $supply->getAdapter()->quoteInto("ID = ?", intval($sid));
            $supply->delete($where);
            $supplyRanking = new Application_Model_DbTable_SupplyRanking();
            $condition = $supplyRanking->getAdapter()->quoteInto("SupplyID = ? ", intval($sid));
            $supplyRanking->delete($condition);
        }
        $this->_helper->getHelper('Json')->sendJson(array('id' => $sid, 'message' => 'Delete Successfully'));
    }

    public function exportAction() {
        $filename = 'supply.csv';
        Zend_Layout::getMvcInstance()->disableLayout();
        Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true);
        $this->getResponse()->setHttpResponseCode(200);
        $this->getResponse()->setHeader('Content-Type', 'application/csv', true);
        $this->getResponse()->setHeader('Content-Disposition', 'inline; filename="' . $filename . '"', true);
        $this->getResponse()->setHeader('Cache-Control', 'public', true);
        $this->getResponse()->setHeader('Pragma', 'public', true);
        $content = "";
        $supply = new Application_Model_DbTable_Supply();
        $records = $supply->fetchAll()->toArray();
        $heads = array_keys($records[0]);
        $content = $content . implode(',', $heads) . "\n";
        foreach ($records as $record) {
            $content = $content . implode(',', array_values($record))."\n";
        }
        $this->getResponse()->setBody($content);
    }

}
